import random
from qcloudsms_py import SmsSingleSender

from . import setttings
from utils.logging import get_logger

logger = get_logger('sms')


def get_code():
    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))

    return code


def send_code(mobile_phone, code, minute=30):
    appid = setttings.APPID
    appkey = setttings.APPKEY
    template_id = setttings.TEMPLATE_ID
    sms_sign = setttings.SMS_SIGN

    phone_numbers = [mobile_phone, ]
    ssender = SmsSingleSender(appid, appkey)
    params = [code, minute]
    try:
        result = ssender.send_with_param(86, phone_numbers[0],
                                         template_id, params, sign=sms_sign, extend="", ext="")
        if result and result.get('result') == 0:
            return True, '发送成功'
        else:
            logger.error('短信发送失败，原因为：%s' % str(result.get('errmsg')))
            return False, str(result.get('errmsg'))
    except Exception as e:
        print(e)
        logger.error('短信发送失败，原因为：%s' % str(e))
        return False, str(e)
